package com.kc.data.common.interceptor;


import com.kc.data.common.annotation.Login;
import com.kc.data.common.exception.CustomException;
import com.kc.data.common.base.StringUtils;
import com.kc.data.common.constants.CommonConstants;
import com.kc.data.common.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 权限(Token)验证
 *
 * @author wangdl
 */
@Component
@Configuration
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private JwtUtils jwtUtils;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Value("${token.expire}")
    private long expire;

    public static final String USER_KEY = "shareUserId";
    private static final Long MILLIS_MINUTE_TEN = 604800L;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        } else {
            return true;
        }

        if (annotation == null) {
            return true;
        }

        //获取用户凭证
        String token = request.getHeader(jwtUtils.getHeader());
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(jwtUtils.getHeader());
        }

        //凭证为空
        if (StringUtils.isBlank(token)) {
            throw new CustomException("登录已失效", HttpStatus.UNAUTHORIZED.value());
        }

        Claims claims = jwtUtils.getClaimByToken(token);
        if (claims == null) {
            throw new CustomException("登录已失效", HttpStatus.UNAUTHORIZED.value());
        }
        Object cacheToken = redisTemplate.opsForValue().get(CommonConstants.REDIS_TOKEN_PREFIX + ":" + claims.getSubject());
        if (!token.equals(cacheToken)) {
            throw new CustomException("登录已失效", HttpStatus.UNAUTHORIZED.value());
        }

        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(USER_KEY, Integer.parseInt(claims.getSubject()));

        long tokenExpire = redisTemplate.getExpire(CommonConstants.REDIS_TOKEN_PREFIX + ":" + claims.getSubject(), TimeUnit.SECONDS);
        if (ObjectUtils.isNotEmpty(cacheToken)) {
            if (tokenExpire <= MILLIS_MINUTE_TEN) {
                redisTemplate.opsForValue().set(CommonConstants.REDIS_TOKEN_PREFIX + ":" + claims.getSubject(), token, expire, TimeUnit.SECONDS);
            }
        } else {
            throw new CustomException("登录已失效", HttpStatus.UNAUTHORIZED.value());
        }

        return true;
    }
}
